// select
window.Vue && Vue.component('layui-select', {
	template: `
<div class="layui-unselect layui-form-select" :class="classs">
	<div class="layui-select-title">
		<input type="hidden" :name="name" :value="selectedItem && selectedItem.value"/>
		<input type="text" placeholder="请选择" :value="selectedItem && selectedItem.title" class="layui-input layui-unselect" @click.stop="showList" readonly/>
		<i class="layui-edge"></i>
	</div>
	<dl class="layui-anim layui-anim-upbit" style="">
		<dd class="layui-select-tips" @click.stop="onSelect(null)">请选择</dd>
		<dd v-for="item in items" :class="{\'layui-this\':isSelectItem(item)}" @click.stop="onSelect(item)">{{item.title}}</dd>
	</dl>
</div>
`,
	model: {
		event: "change"
	},
	props: {
		items: {
			type: Array,
			default: []
		},
		name: String,
		value: null,
	},
	computed: {
		classs: function() {
			return {
				'layui-form-selected': this.isShowList
			};
		}
	},
	data: function() {
		return {
			selectedItem: null,
			isShowList: false
		};
	},
	created: function() {
		const self = this;
		const handler = function() {
			self.isShowList = false;
		};
		document.addEventListener('click', handler);
		this.$once('hook:beforeDestroy', function() {
			document.removeEventListener('click', handler);
		});
		this.updateRender();
	},
	methods: {
		showList: function() {
			this.isShowList = true;
		},
		isSelectItem: function(item) {
			return this.selectedItem && item.value === this.selectedItem.value;
		},
		onSelect: function(item) {
			this.selectedItem = item;
			this.isShowList = false;
			this.$emit('change', item ? item.value : null);
		},
		updateRender: function() {
			for (let i = 0; i < this.items.length; i++) {
				const item = this.items[i];
				if (this.value === item.value) {
					this.selectedItem = item;
					break;
				}
			}
		}
	},
	watch: {
		value: 'updateRender'
	}
});
